﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
using System.IO;

namespace SplenetiX
{
   [Serializable]
    public class LevelManager
    {
        Level currentLevel;
        Level  levelOne;
        Level levelTwo;
        Texture2D blocExit;
        public int index;

        List<Level> listLevel = new List<Level>();

        float timer = 0f;

        public LevelManager()
        {
        }

        public Level CurrentLevel
        {
            get { return currentLevel; }
            set { this.currentLevel = value; }
        }

        public void Init(ContentManager content)
        {
            blocExit = content.Load<Texture2D>("Tiles&Background\\exit");

            index = 1;

            levelOne = new Level(1);
            levelTwo = new Level(2);

            listLevel.Add(levelOne);
            listLevel.Add(levelTwo);

            currentLevel = levelOne;

            foreach (Level l in listLevel)
            {
                l.InitTailleLevel();
            }
        }

        public void Update(GameTime gameTime, ContentManager content, Personnage player, Game1 game)
        {
           
           timer += (float)gameTime.ElapsedGameTime.TotalSeconds;

           if (timer > 0.5f)
           {
               Rectangle rectEndLevel = new Rectangle((int)Constant.EndPoint.X, (int)Constant.EndPoint.Y, blocExit.Width, blocExit.Height);

               if (rectEndLevel.Intersects(player.Rectangle))
               {
                   currentLevel.ResetEnnemis();
                   

                   if (this.CurrentLevel.Numero <= listLevel.Count)
                      index++;

                   changeCurrentLevel(index, content);

                   player.Position = Constant.EntryPoint;
                   player.Health = Constant.PlayerHealth;
                   Constant.SetGravity(CurrentLevel.Gravity);
                   timer = 0f;

                   game.SaveGame();
               }
           }

        }

        public void changeCurrentLevel(int numRech, ContentManager content)
        {
            foreach (Level l in listLevel)
            {
                if (l.Numero == numRech)
                {
                    currentLevel = l;
                    index = l.Numero;
                }
            }
            CurrentLevel.ResetEnnemis();
            CurrentLevel.InitTailleLevel();
            CurrentLevel.ConfigLevel();
            CurrentLevel.Parser(content);
            CurrentLevel.Load(content);
        }
    }
}
